package com.nvelickovic10.snake.beans.engine;

import javax.swing.JOptionPane;

import com.nvelickovic10.snake.beans.game.GameSave;
import com.nvelickovic10.snake.beans.snake.Snake;
import com.nvelickovic10.snake.gui.GameWindow;
import com.nvelickovic10.snake.main.AppCore;

public class Engine extends Thread {

	private GameWindow gw;

	public Engine() {
		gw = new GameWindow();
		AppCore.getInstance().setGw(gw);
	}

	@Override
	public void run() {
		while (true) {
			if (AppCore.getInstance().isGameOn()) {
				try {
					sleep(AppCore.getInstance().getSpeed());
				} catch (InterruptedException e) {
				}
				if (gw.isActive() && !AppCore.getInstance().isPaused()) {
					Snake.getInstance().turnSnake(
							Snake.getInstance().getHead().getDirrection());
					gw.repaint();
				} else {
					AppCore.getInstance().setPaused(true);
					if (!gw.isDisposingg()
							&& !AppCore.getInstance().isLoading()) {
						int resp = JOptionPane.showConfirmDialog(null,
								"PAUSED!\nSAVE GAME?", "PAUSED",
								JOptionPane.YES_NO_OPTION);
						if (resp == JOptionPane.YES_OPTION) {
							GameSave gs = new GameSave();
							gs.setBody(Snake.getInstance().getBody());
							gs.setFoodPosition(AppCore.getInstance().getFood()
									.getPosition());
							gs.setPoints(AppCore.getInstance().getPoints());
							gs.setSpeedFactor(AppCore.getInstance().getSpeed());
							gs.setUsername(AppCore.getInstance().getUsername());
							gs.save();
							gs = null;
						}
						AppCore.getInstance().setPaused(false);
					}
				}

			}
			if (gw.isDisposed())
				System.exit(0);
		}
	}
}
